require 'config/environment'

task :read_jlpt_vocabularies do
  raise "IO Error: Please specify file(UTF-8)" unless ENV.has_key? "doc"
  raise "Parameter Error:Pease Specify Vocabulary Level." unless ENV.has_key? "lv"
  #
  rs = ENV.has_key?("rs") ? ENV["rs"] : " "
  level = (ENV["lv"].to_f + 1.0) / 5.0
  new_words = 0
  #
  require 'csv'
  CSV.open(ENV["doc"],"r",rs) do |row|
    next if row.first == "#"
    word = row.compact
    next if word.empty?
    next if /~|（.+）/ =~ word.join
    #
    dic = Dictionary.find(:all,:conditions => {:index => word.first})
    if word.size > 1
      candidates = dic.select{|one| one.entry["reading"] == word[1].to_s }
      candidates.each do |entry|
        next if entry.jlpt_level != nil && entry.jlpt_level > level
        entry.update_attribute :jlpt_level,level
      end
      next unless candidates.empty?
    end
    #
    unless dic.empty?
      dic.each do |entry|
        next if entry.jlpt_level != nil && entry.jlpt_level > level
        entry.update_attribute :jlpt_level,level
      end
    else
      Dictionary.create :index => word.first,:entry => {"surface" => word.first.to_s},:jlpt_level => level
      new_words += 1
    end
    
  end
  #
  puts "create new #{new_words} entries" if new_words > 0
end